﻿using Microsoft.AspNetCore.Authorization;

namespace EMall.Extensions
{
    public class ScopesAuthorizationRequirement : AuthorizationHandler<ScopesAuthorizationRequirement>, IAuthorizationRequirement
    {
        public ScopesAuthorizationRequirement(IEnumerable<string> allowedScopes)
        {
            if (!allowedScopes.Any())
            {
                throw new InvalidOperationException("allowedScopes can not be empty");
            }
            AllowedScopes = allowedScopes;
        }
        public IEnumerable<string> AllowedScopes { get; }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ScopesAuthorizationRequirement requirement)
        {
            if (context.User != null)
            {
                var found = false;

                foreach (var scope in requirement.AllowedScopes)
                {
                    if (context.User.Claims.Any(o => o.Value == scope))
                    {
                        found = true;
                        break;
                    }
                }

                if (found)
                {
                    context.Succeed(requirement);
                }
            }
            return Task.CompletedTask;
        }
         
        public override string ToString()
        {
            var scopes = $"User must have one of the following scopes: ({string.Join("|", AllowedScopes)})"; 
            return $"{nameof(ScopesAuthorizationRequirement)}:{scopes}";
        }
    }
}
